package upload.controller;


import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.http.Method;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/minio")
public class FileUploadController {

    @Resource
    private MinioClient minioClient;
    private final String bucketName = "test";

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder().object(file.getOriginalFilename())
                    .bucket(bucketName)
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(),file.getSize(),-1).build();

            minioClient.putObject(objectArgs);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
    @PostMapping("/upload-copy")
    public String uploadFile2(@RequestParam("file") MultipartFile file) {
        try {
            // 上传文件到 MinIO
            PutObjectArgs objectArgs = PutObjectArgs.builder()
                    .object(file.getOriginalFilename())
                    .bucket("test")
                    .contentType(file.getContentType())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .build();
            minioClient.putObject(objectArgs);

            // 生成签名 URL
            String url = minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .bucket("test")
                            .object(file.getOriginalFilename())
                            .method(Method.GET)
                            .expiry(60 * 60) // 1 hour expiry
                            .build());
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
    @PostMapping("/upload2")
    public String uploadFiles(@RequestParam("files") MultipartFile[] files) {
        try {
            for (MultipartFile file : files) {
                // 构建 PutObjectArgs 对象
                PutObjectArgs objectArgs = PutObjectArgs.builder()
                        .object(file.getOriginalFilename())  // 文件名
                        .bucket(bucketName)  // 桶名
                        .contentType(file.getContentType())  // 文件类型
                        .stream(file.getInputStream(), file.getSize(), -1)  // 文件输入流
                        .build();

                // 上传文件到 MinIO
                minioClient.putObject(objectArgs);
            }
            return "ok";  // 返回成功消息
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();  // 返回错误消息
        }
    }


}
